//
//  SwipeTableViewCell.m
//  quanminzhekou
//
//  Created by zxl on 15/1/15.
//  Copyright (c) 2015年 zhongqinglongtu. All rights reserved.
//

#import "SwipeTableViewCell.h"

@interface SwipeTableViewCell ()
@property (nonatomic) CGRect currentFrame;
@end

@implementation SwipeTableViewCell

- (void)awakeFromNib {
    
    self.contentView.backgroundColor = [UIColor whiteColor];
    self.isSwiping = NO;
    self.isCanSwip = YES;
    self.isHasSelectedType = YES;
    
    UIPanGestureRecognizer* panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
    panGestureRecognizer.delegate = self;
    [self addGestureRecognizer:panGestureRecognizer];
    
    self.animationDuration = 0.2f;
    self.backViewbackgroundColor = [UIColor whiteColor];
    self.panElasticity = YES;//阻尼
    self.panElasticityStartingPoint = 0;//阻尼开始点
    
    UIView *backgroundView = [[UIView alloc] initWithFrame:self.frame];
    backgroundView.backgroundColor = [UIColor whiteColor];
    self.backgroundView = backgroundView;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    // Configure the view for the selected state
}

-(void)prepareForReuse {
    [super prepareForReuse];
}

-(void)didStartSwiping {
    [self.backgroundView addSubview:self.backView];
    self.backView.frame = CGRectMake(0, 0, CGRectGetWidth(self.contentView.frame), 98);
    
    self.currentFrame = self.contentView.frame;
}

- (void)animateContentViewForPoint:(CGPoint)point velocity:(CGPoint)velocity {
    self.contentView.frame = CGRectOffset(self.currentFrame, point.x, 0);
}

- (void)resetCellFromPoint:(CGPoint)point velocity:(CGPoint)velocity {
    if (point.x < 0) {
        if (-point.x < 75 / 2.0) {
            [self resetContentViewWithFromPoint:point velocity:velocity animating:YES];
        } else {
            [UIView animateWithDuration:self.animationDuration animations:^{
                self.contentView.frame = CGRectOffset(self.currentFrame, -75, 0);
            } completion:^(BOOL finished) {
                self.isSwiping = YES;
            }];
        }
    } else {
        [self resetContentViewWithFromPoint:point velocity:velocity animating:YES];
    }
}


- (UIView*)backView {
    if (!_backView) {
        _backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.contentView.frame), 98)];
        _backView.backgroundColor = self.backViewbackgroundColor;
        _backView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    }
    return _backView;
}

- (void)cleanupBackView {
    [_backView removeFromSuperview];
    _backView = nil;
}

- (void)resetContentViewWithFromPoint:(CGPoint)point velocity:(CGPoint)velocity animating:(BOOL)animating {
    __weak typeof(self) weakSelf = self;
    
    void (^resetContentOffsetAnimations)() = ^{
        weakSelf.contentView.frame = CGRectOffset(self.contentView.bounds, 0, 0);
    };
    
    void (^resetContentOffsetCompletion)(BOOL) = ^(BOOL finished) {
        [weakSelf cleanupBackView];
        weakSelf.isSwiping = NO;
        
        if ([weakSelf.delegate respondsToSelector:@selector(swipeTableViewCellDidResetState:fromPoint:velocity:)]) {
            [weakSelf.delegate swipeTableViewCellDidResetState:self fromPoint:point velocity:velocity];
        }
    };
    
    if (animating) {
        CGFloat panOffset = (point.x * 0.55f * CGRectGetWidth(self.frame)) / (point.x * 0.55f + CGRectGetWidth(self.frame));
        [UIView animateWithDuration:self.animationDuration animations:^{
            self.contentView.frame = CGRectOffset(self.contentView.bounds, 0 + (panOffset * 0.03), 0);
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:.1 animations:^{
                self.contentView.frame = CGRectOffset(self.contentView.bounds, 0 - (panOffset * 0.02), 0);
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:.1 animations:resetContentOffsetAnimations completion:resetContentOffsetCompletion];
            }];
        }];
    } else {
        resetContentOffsetAnimations();
        resetContentOffsetCompletion(YES);
    }
}

- (void)setIsSwiping:(BOOL)isSwiping {
    _isSwiping = isSwiping;
    
    if (!self.isHasSelectedType) {
        return;
    }
    
    if (_isSwiping) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
    } else {
        self.selectionStyle = UITableViewCellSelectionStyleDefault;
    }
}

- (void)setIsHasSelectedType:(BOOL)isHasSelectedType {
    _isHasSelectedType = isHasSelectedType;
    if (_isHasSelectedType) {
        self.selectionStyle = UITableViewCellSelectionStyleDefault;
    } else {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
    }
}

#pragma mark -
-(void)handlePanGesture:(UIPanGestureRecognizer *)panGestureRecognizer {
    CGPoint translation = [panGestureRecognizer translationInView:panGestureRecognizer.view];
    CGPoint velocity = [panGestureRecognizer velocityInView:panGestureRecognizer.view];
    CGFloat panOffset = translation.x;
    if (self.panElasticity) {
        if (ABS(translation.x) > self.panElasticityStartingPoint) {
            CGFloat width = CGRectGetWidth(self.frame);
            CGFloat offset = fabs(translation.x);
            panOffset = (offset * 0.55f * width) / (offset * 0.55f + width);
            panOffset *= translation.x < 0 ? -1.0f : 1.0f;
            if (self.panElasticityStartingPoint > 0) {
                panOffset = translation.x > 0 ? panOffset + self.panElasticityStartingPoint / 2 : panOffset - self.panElasticityStartingPoint / 2;
            }
        }
    }
    
    CGPoint actualTranslation = CGPointMake(panOffset, translation.y);
    if (panGestureRecognizer.state == UIGestureRecognizerStateBegan) {
        [self didStartSwiping];
        [self animateContentViewForPoint:actualTranslation velocity:velocity];
    } else if (panGestureRecognizer.state == UIGestureRecognizerStateChanged) {
        [self animateContentViewForPoint:actualTranslation velocity:velocity];
    } else if (panGestureRecognizer.state == UIGestureRecognizerStateEnded) {
        [self resetCellFromPoint:actualTranslation velocity:velocity];
    }
}

#pragma mark - UIGestureRecognizerDelegate
-(BOOL)gestureRecognizerShouldBegin:(UIPanGestureRecognizer *)panGestureRecognizer {
    if ([panGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] && self.isCanSwip) {
        CGPoint translation = [panGestureRecognizer translationInView:[self superview]];
        if ((0 == CGRectGetMinX(self.contentView.frame) && translation.x < 0) ||
            (0 > CGRectGetMinX(self.contentView.frame) && translation.x > 0)) {
            return YES;
        } else {
            return NO;
        }
    } else {
        return NO;
    }
}

@end
